import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:fake_handwriting/Util.dart';
import 'package:fake_handwriting/generated/l10n.dart';
import 'package:fake_handwriting/http/bean/file_bean.dart';
import 'package:fake_handwriting/http/http.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class OnlineFont extends StatefulWidget {
  const OnlineFont({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => OnlineFontPage();
}
class FontLoadState {
  int process;
  FontLoadState(this.process);
}
class OnlineFontPage extends State<OnlineFont> {
  List<String> urls = [];
  List<FileBean?> beans = [];
  List<FontLoadState> status = [];


  List<CancelToken>tokens=[];
  var dir = "";
  @override
  void initState() {
    super.initState();
    init();
  }
  @override
  void dispose() {
    for (var element in tokens) {
      element.cancel();
    }
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    String type = ModalRoute.of(context)?.settings.arguments as String;
    return Scaffold(
      body: SafeArea(
          child: GridView.custom(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                mainAxisSpacing: 2,
                crossAxisSpacing: 2,
              ),
              childrenDelegate: SliverChildBuilderDelegate((context, index) {
                return InkWell(
                  onTap: () {
                    if (type == "choose") {
                      if(status[index].process==100){
                        Navigator.pop(context, beans[index]);
                      }else{
                        Util.toast(S.of(context).notDownloadedCannotSelect);
                      }
                    }
                  },
                  onLongPress: () async {
                    var res = await showDialog(
                        context: context,
                        builder: (context) => SimpleDialog(
                              title: Text(S.of(context).selectAction),
                              children: <Widget>[
                                SimpleDialogOption(
                                  child:Text(S.of(context).delete),
                                  onPressed: () {
                                    Navigator.pop(context, S.of(context).delete);
                                  },
                                ),
                                const Divider(),
                                SimpleDialogOption(
                                  child: Text(S.of(context).share),
                                  onPressed: () async {
                                    Navigator.pop(context,S.of(context).share);
                                    if(status[index].process == 100){
                                      await Util.shareFile("$dir${beans[index]!.filename}");
                                    }else{
                                     Util.toast(S.of(context).theFontHasNotBeenDownloaded);
                                    }
                                  },
                                ),
                              ],
                            ));
                    if (res == S.of(context).delete) {
                      try {
                        await Http.delete_file("${beans[index]!.id}");
                      } catch (e) {
                      }
                    }
                    await init();
                  },
                  child: Container(
                    decoration:
                        BoxDecoration(border: Border.all(color: Colors.blue)),
                    child: Center(
                      child: getText(index),
                    ),
                  ),
                );
              }, childCount: urls.length))),
      appBar: AppBar(
        title:Text(S.of(context).myFont),
      ),
      floatingActionButton: (type == "choose")
          ? Container()
          : FloatingActionButton(
              onPressed: () async {
                FilePickerResult? result = await FilePicker.platform.pickFiles();
                if (result != null) {
                  Util.showLoading(context);
                  try {
                    await Http.upload(result.files.single.path.toString(), result.files.single.name, "font");
                    Util.toast(S.of(context).uploadSuccessful);
                    Navigator.pop(context);
                  } catch (e) {
                    Navigator.pop(context);
                    Util.toast("$e");
                  }
                }
                await init();
              },
              child: const Icon(Icons.cloud_upload),
            ),
    );
  }
  Future<void> init() async {
    urls = [];
    beans = (await Http.get_files("font"))!;
    dir = await Util.getCacheDir();
    for (var element in beans) {
      urls.add(Http.BASE_URL+element!.path.toString());
      status.add(FontLoadState(0));
    }
    setState(() {});
    for (var i = 0; i < beans.length; i++) {
      var file = File("$dir${beans[i]!.id}${beans[i]!.filename}");
      if (await file.exists()) {
        status[i].process = 100;
        loadFont(file,beans[i]!.id.toString());
      } else {
        CancelToken token=CancelToken();
        tokens.add(token);
        await Dio().download(Http.BASE_URL+beans[i]!.path.toString(), "$dir${beans[i]!.id}${beans[i]!.filename}", onReceiveProgress: (a, b) async {
          status[i].process = ((a / b) * 100).toInt();
          setState(() {});
          if (status[i].process == 100) {
            loadFont(File("$dir${beans[i]!.id}${beans[i]!.filename}"), beans[i]!.id.toString());
          }
        },cancelToken: token);
      }
    }
  }
  loadFont(file,String id) async {
    var fontLoader = FontLoader("family_$id");
    fontLoader.addFont(Util.getByteData(file));
    await fontLoader.load();
    setState(() {});
  }
  getText(int index) {
    if (status[index].process == 100) {
      return Text(
        "${S.of(context).fakeHandwriting}\n\nFake-Handwriting",
        style: TextStyle(
            fontFamily: "family_${beans[index]!.id}",
            fontSize: 18),
      );
    } else {
      return Text("${S.of(context).downloading}${status[index].process}%");
    }
  }
}